﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace ArgusLight.Threading
{
	public class Timer : DispatcherTimer
	{
		public TimeSpan Duration { get; private set; }
		private DateTime dtStart;
		//private Dispatcher dispatcher;

		public Timer()
			: base()
		{
			//this.dispatcher = dispatcher;
			this.IsEnabled = false;
			base.Tick += (a, b) =>
				{
					base.Stop();
					this.Duration = DateTime.Now - this.dtStart;
					this.dtStart = DateTime.Now;
					//this.dispatcher.BeginInvoke(this.DispatcherMethodTick);
					//this.DispatcherMethodTick();
					if (this.Tick != null)
						this.Tick(this, EventArgs.Empty);
					TimeSpan interval = this.Interval - (DateTime.Now - this.dtStart);
					if (interval.Ticks > 0)
						base.Interval = interval;
					else
						base.Interval = this.Interval;
					base.Start();
				};
		}

		public new event EventHandler Tick;

		//private void DispatcherMethodTick()
		//{
		//	if (this.Tick != null)
		//		this.Tick(this, EventArgs.Empty);
		//	TimeSpan interval = this.Interval - (DateTime.Now - this.dtStart);
		//	if (interval.Ticks > 0)
		//		base.Interval = interval;
		//	else
		//		base.Interval = this.Interval;
		//	base.Start();
		//}

		public new bool IsEnabled { get; private set; }
		public new TimeSpan Interval { get; set; }

		public new void Start()
		{
			this.IsEnabled = true;
			this.dtStart = DateTime.Now;
			base.Start();
		}

		public new void Stop()
		{
			base.Stop();
			this.Duration = DateTime.Now - this.dtStart;
			this.IsEnabled = false;
		}
	}
}
